package com.ruoyi.safe.controller.api;


import cn.hutool.core.date.DateUtil;
import com.github.pagehelper.PageInfo;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.R;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.core.domain.model.LoginUser;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.PageUtils;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.quality.domain.TQualityFileItem;
import com.ruoyi.quality.service.ITQualityEnterCheckService;
import com.ruoyi.quality.service.ITQualityFileItemService;
import com.ruoyi.safe.domain.BizProjectCheck;
import com.ruoyi.safe.domain.BizProjectCheckRecord;
import com.ruoyi.safe.domain.dto.BizProjectCheckAppDTO;
import com.ruoyi.safe.domain.dto.BizProjectCheckRecordDTO;
import com.ruoyi.safe.domain.dto.EntityIdAppDTO;
import com.ruoyi.safe.domain.dto.EntityIdsAppDTO;
import com.ruoyi.safe.service.IBizProjectCheckRecordService;
import com.ruoyi.safe.service.IBizProjectCheckService;
import com.ruoyi.system.service.ISysUserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;


/**
 * 项目自查接口(app端)--张鹏
 */
@Slf4j
@RestController
@RequestMapping("/api/project/check")
public class ProjectCheckController extends BaseController {
    @Autowired
    IBizProjectCheckService bizProjectCheckService;
    @Autowired
    IBizProjectCheckRecordService bizProjectCheckRecordService;
    @Autowired
    ISysUserService sysUserService;

    @Autowired
    ITQualityEnterCheckService iTQualityEnterCheckService;
    /**
     * 项目自查分页数据(与用户相关的)
     * @param
     * @return
     */
    @PostMapping("/relatedList")
    public R<Object>  relatedList(@RequestBody BizProjectCheckAppDTO bizProjectCheckAppDTO)
    {
        LoginUser loginUser = SecurityUtils.getLoginUser();
        Integer pageNo = bizProjectCheckAppDTO.getPageNum()==null?1:bizProjectCheckAppDTO.getPageNum();
        Integer pageSize = bizProjectCheckAppDTO.getPageSize()==null?10:bizProjectCheckAppDTO.getPageSize();
        PageUtils.startPage(pageNo,pageSize);
        PageUtils.orderBy("create_time desc");
        BizProjectCheck bizProjectCheck = new BizProjectCheck();
        bizProjectCheck.setCheckType(bizProjectCheckAppDTO.getCheckType());
        bizProjectCheck.setCheckPeople(loginUser.getUsername());
        bizProjectCheck.setProjectId(bizProjectCheckAppDTO.getProjectId());
//        List<BizProjectCheck> bizProjectCheckList = bizProjectCheckService.selectProjectCheckListForApp(bizProjectCheck,bizProjectCheckAppDTO.getUserName());
//        bizProjectCheck.setSearchType("1");
        if("1".equals(bizProjectCheckAppDTO.getSearchType())){
            bizProjectCheck.setSearchType("1");
        }else{
            bizProjectCheck.setSearchType("0");
        }
        List<BizProjectCheck> bizProjectCheckList = bizProjectCheckService.selectProjectCheckListForQuality(bizProjectCheck);
        return R.ok(new PageInfo<>(bizProjectCheckList));
    }


    /**
     * 项目自查分页数据(与用户无关)
     * @param
     * @return
     */
    @PostMapping("/list")
    public R<Object>  list(@RequestBody @Validated BizProjectCheckAppDTO bizProjectCheckAppDTO)
    {
        SysUser sysUser = sysUserService.selectUserByUserName(bizProjectCheckAppDTO.getUserName());
        if (sysUser == null) {
            throw new ServiceException(StringUtils.format("用户信息不存在：{}", bizProjectCheckAppDTO.getUserName()));
        }
        Integer pageNo = bizProjectCheckAppDTO.getPageNum();
        Integer pageSize = bizProjectCheckAppDTO.getPageSize();
        PageUtils.startPage(pageNo,pageSize);
        PageUtils.orderBy("create_time desc");
        BizProjectCheck bizProjectCheck = new BizProjectCheck();
        bizProjectCheck.setCheckType(bizProjectCheckAppDTO.getCheckType());
        bizProjectCheck.setProjectId(bizProjectCheckAppDTO.getProjectId());
        List<BizProjectCheck> bizProjectCheckList = bizProjectCheckService.selectProjectCheckListForApp(bizProjectCheck,bizProjectCheckAppDTO.getUserName());
        return R.ok(new PageInfo<>(bizProjectCheckList));
    }

    /**
     * 新增项目自检
     * @param bizProjectCheckAppDTO
     * @return
     */
    @PostMapping("/add")
    public AjaxResult add(@RequestBody @Validated BizProjectCheckAppDTO bizProjectCheckAppDTO)
    {
        SysUser sysUser = sysUserService.selectUserByUserName(bizProjectCheckAppDTO.getUserName());
        if (sysUser == null) {
            throw new ServiceException(StringUtils.format("用户信息不存在：{}", bizProjectCheckAppDTO.getUserName()));
        }
        BizProjectCheck bizProjectCheck = new BizProjectCheck();
        BeanUtils.copyProperties(bizProjectCheckAppDTO,bizProjectCheck);
        bizProjectCheck.setCreateBy(bizProjectCheckAppDTO.getUserName());
        return toAjax(bizProjectCheckService.insertBizProjectCheckNoLogin(bizProjectCheck));
    }

    /**
     * 修改项目自检
     * @param bizProjectCheckAppDTO
     * @return
     */
    @PostMapping("/update")
    public AjaxResult update(@RequestBody @Validated BizProjectCheckAppDTO bizProjectCheckAppDTO)
    {
        SysUser sysUser = sysUserService.selectUserByUserName(bizProjectCheckAppDTO.getUserName());
        if (sysUser == null) {
            throw new ServiceException(StringUtils.format("用户信息不存在：{}", bizProjectCheckAppDTO.getUserName()));
        }
        if(bizProjectCheckAppDTO.getId() == null){
            throw new ServiceException("项目自检ID不能为空");
        }
        BizProjectCheck bizProjectCheck = new BizProjectCheck();
        BeanUtils.copyProperties(bizProjectCheckAppDTO,bizProjectCheck);
        bizProjectCheck.setCreateBy(bizProjectCheckAppDTO.getUserName());
        return toAjax(bizProjectCheckService.updateBizProjectCheckNoLogin(bizProjectCheck));
    }

    /**
     * 查看详情 + 隐患记录
     * @param entityIdAppDTO
     * @return
     */
    @PostMapping("/info")
    public AjaxResult info(@RequestBody @Validated EntityIdAppDTO entityIdAppDTO){
        SysUser sysUser = sysUserService.selectUserByUserName(entityIdAppDTO.getUserName());
        if (sysUser == null) {
            throw new ServiceException(StringUtils.format("用户信息不存在：{}", entityIdAppDTO.getUserName()));
        }
        BizProjectCheck bizProjectCheck = bizProjectCheckService.selectBizProjectCheckById(entityIdAppDTO.getId());
        //是否有权限新增记录
        if(bizProjectCheck.getCheckPeople() != null){
            List<String> checkPeoples = Arrays.asList(bizProjectCheck.getCheckPeople().split(","));
            if(checkPeoples.contains(entityIdAppDTO.getUserName())){
                bizProjectCheck.setHasAddRecordPermission(true);
            }else{
                bizProjectCheck.setHasAddRecordPermission(false);
            }
        }
        //当前id下的所有隐患记录
        List<BizProjectCheckRecord> bizProjectCheckRecords = bizProjectCheckRecordService.selectCheckRecordListById(entityIdAppDTO.getId());
        List<BizProjectCheckRecord> myBizProjectCheckRecords = bizProjectCheckRecords.stream().filter(bizProjectCheckRecord->entityIdAppDTO.getUserName().equals(bizProjectCheckRecord.getCheckPeople())).collect(Collectors.toList());
        //我的待办的隐患数量
        long inHandDangerCount = myBizProjectCheckRecords.stream().filter(a -> {
            boolean flag = "4".equals(a.getHiddenDangerStatus()) || "2".equals(a.getHiddenDangerStatus()) || "1".equals(a.getHiddenDangerStatus());
            return flag && a.getCheckPeople().equals(entityIdAppDTO.getUserName());
        }).count();
        bizProjectCheck.setInHandDangerCount(inHandDangerCount);
        bizProjectCheck.setBizProjectCheckRecords(bizProjectCheckRecords);
        bizProjectCheck.setMyBizProjectCheckRecords(myBizProjectCheckRecords);
        return AjaxResult.success(bizProjectCheck);
    }

    /**
     * 删除检查记录中的数据
     * @param entityIdAppDTO
     * @return
     */
    @PostMapping("/deleteCheckRecordById")
    public AjaxResult deleteCheckRecordsById(@RequestBody @Validated EntityIdAppDTO entityIdAppDTO){
        SysUser sysUser = sysUserService.selectUserByUserName(entityIdAppDTO.getUserName());
        if (sysUser == null) {
            throw new ServiceException(StringUtils.format("用户信息不存在：{}", entityIdAppDTO.getUserName()));
        }
        return toAjax(bizProjectCheckRecordService.deleteBizProjectCheckRecordById(entityIdAppDTO.getId()));
    }

    /**
     * 批量删除检查记录中的数据
     * @param entityIdsAppDTO
     * @return
     */
    @PostMapping("/deleteCheckRecordByIds")
    public AjaxResult deleteCheckRecordsByIds(@RequestBody @Validated EntityIdsAppDTO entityIdsAppDTO){
        SysUser sysUser = sysUserService.selectUserByUserName(entityIdsAppDTO.getUserName());
        if (sysUser == null) {
            throw new ServiceException(StringUtils.format("用户信息不存在：{}", entityIdsAppDTO.getUserName()));
        }
        return toAjax(bizProjectCheckRecordService.deleteBizProjectCheckRecordByIds(entityIdsAppDTO.getIds()));
    }

    /**
     * 新增项目自检的隐患记录
     * @param bizProjectCheckRecordDTO
     * @return
     */
    @PostMapping("/addCheckRecord")
    public AjaxResult addCheckRecord(@RequestBody @Validated BizProjectCheckRecordDTO bizProjectCheckRecordDTO){
        SysUser sysUser = sysUserService.selectUserByUserName(bizProjectCheckRecordDTO.getUserName());
        if (sysUser == null) {
            throw new ServiceException(StringUtils.format("用户信息不存在：{}", bizProjectCheckRecordDTO.getUserName()));
        }
        return toAjax(bizProjectCheckRecordService.insertBizProjectCheckRecordNoLogin(bizProjectCheckRecordDTO));
    }

    /**
     * 修改项目自检状态为已结束或取消
     * @param entityIdAppDTO
     * @return
     */
    @PostMapping("/updateProjectStatus")
    public AjaxResult updateProjectStatus(@RequestBody EntityIdAppDTO entityIdAppDTO){
        LoginUser loginUser = SecurityUtils.getLoginUser();
        BizProjectCheck bizProjectCheck = new BizProjectCheck();
        bizProjectCheck.setId(entityIdAppDTO.getId());
        bizProjectCheck.setUpdateBy(loginUser.getUsername());
        bizProjectCheck.setUpdateTime(DateUtils.getNowDate());
        bizProjectCheck.setStatus(entityIdAppDTO.getStatus());
        if("3".equals(bizProjectCheck.getStatus())){
            bizProjectCheck.setComplateCheckTime(DateUtil.date());
        }
        return toAjax(bizProjectCheckService.updateProjectCheckStatus(bizProjectCheck));
    }


    /**
     * 项目自检拆分
     * @param listFileItems
     */
    @Log(title = "项目自检拆分", businessType = BusinessType.INSERT)
    @PostMapping("/splitFile")
    public AjaxResult splitFile(@RequestBody List<TQualityFileItem> listFileItems)
    {
        return toAjax(bizProjectCheckService.splitFiles(listFileItems));
    }

    /**
     * 点击质量问题数字，获取质量问题明细列表
     * @param tQualityFileItem
     */
    @Log(title = "点击质量问题数字，获取质量问题明细列表", businessType = BusinessType.INSERT)
    @PostMapping("/getQualityProblemList")
    public R<Object> getQualityProblemList(@RequestBody TQualityFileItem tQualityFileItem)
    {
        List<TQualityFileItem> qualityFileItems= bizProjectCheckService.getQualityProblemList(String.valueOf(tQualityFileItem.getFileId()));
        return R.ok(qualityFileItems);
    }
}
